package cool.taomu.software.fig.spring.example;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import cool.taomu.software.fig.core.CreateMqttClient;
import cool.taomu.software.fig.mqtt.broker.MQTTBroker;
import cool.taomu.software.fig.mqtt.client.paho.MQTTSender;
import cool.taomu.software.fig.mqtt.client.paho.MQTTSubscriber;
import cool.taomu.software.fig.mqtt.client.paho.entity.SenderEntity;
import cool.taomu.software.fig.springutils.FigSpringPlugin;

/***
 * @author rcmu
 */
@SpringBootApplication
@ComponentScan(value = { "cool.taomu.software.fig.spring.example" })
public class DemoMain2  {
	private static ExecutorService exec = Executors.newCachedThreadPool(new ThreadFactory() {
		public Thread newThread(Runnable r) {
			return new Thread(r);
		}
	});
	
	@Autowired
	FigSpringPlugin fig;

	private static void startServer() throws InterruptedException {
		System.err.println("start server");
		exec.submit(new Runnable() {
			@Override
			public void run() {
				MQTTBroker.start();
			}
		});
		TimeUnit.SECONDS.sleep(2);
	}

	public static void main(String[] args) throws InterruptedException, IOException {
		SpringApplication.run(DemoMain2.class, new String[] {});

		startServer();
		startClient();
		// perl();
		// TODO 采集代码
		TimeUnit.SECONDS.sleep(10);
		MQTTSender sender = new MQTTSender();
		sender.publish(new SenderEntity("start").ip("127.0.0.1").port(1883).message(""));

	}

	private static void startClient() throws InterruptedException {
		System.err.println("start client");
		CreateMqttClient client = new CreateMqttClient();
		List<MQTTSubscriber> subs = client.create(Example.class);
		subs.forEach(it -> exec.submit(it));
		TimeUnit.SECONDS.sleep(10);
	}
}
